package wjh.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Component
public class LoginInterCeptor implements HandlerInterceptor {
    //拦截方法 true 放行 false 拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        //1.获取请求路径
        String url = request.getRequestURL().toString();
        if (url.contains("login")){
            //登录功能，放行
            return true;
        }
        //3. 获取用户登录状态，假设使用Session来存储登录信息
        HttpSession session = request.getSession(false); // false 表示不会创建新会话
        Boolean isLoggedIn = (session != null) ? (Boolean) session.getAttribute("isLoggedIn") : false;


        //4. 如果没有登录，拦截请求
        if (isLoggedIn == null || !isLoggedIn) {
            if (url.contains("adminInfo")){
                response.sendRedirect("/jsp/login_admin.jsp"); // 重定向到登录页面
            }else {
                response.sendRedirect("/jsp/login.jsp"); // 重定向到登录页面
            }
            return false; // 拦截请求
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("post");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("after");
    }
}

